<?php
/**
 * Created by ephp
 * User: 22071
 * Date: 2019/6/14
 * Email: <zhendongdong@foxmail.com>
 */

namespace paper;

class Loader
{

    private static $namespaceMap = [
        "paper" => PAPERPHP . DIRECTORY_SEPARATOR . 'library',
    ];

    public static function register()
    {
        if (COMPOSER) {
            $autoLoadFile = ROOT . '/vendor/autoload.php';
            if (!is_file($autoLoadFile)) {
                die("composer 未正确安装");
            }
            require_once($autoLoadFile);
        } else {
            spl_autoload_register("paper\\Loader::autoload");
        }
    }

    /**
     * @param $class_name
     * @throws \Exception
     */
    public static function autoload($class_name)
    {
        $classPath = self::parseClassName($class_name);
        if (is_file($classPath)) {
            self::import($classPath);
        }
    }

    private static function parseClassName($className)
    {
        $classNameArr = explode('\\', $className, 2);
        $namespace    = $classNameArr[0];
        $classpath    = $classNameArr[1] ?? '';
        $classpath    = str_replace("\\", DIRECTORY_SEPARATOR, $classpath);
        if (array_key_exists($namespace, self::$namespaceMap)) {
            $baseDir = self::$namespaceMap[$namespace];
        } else {
            $baseDir = ROOT . DIRECTORY_SEPARATOR . $namespace;
        }
        $path = $baseDir . DIRECTORY_SEPARATOR . $classpath . '.php';
        return $path;
    }

    /**
     * @param $class
     */
    private static function import($class)
    {
        require($class);
    }


}